package engine.gui.popup;

import java.util.ArrayList;

public class PopupManager {

	private ArrayList<Popup> popups;
	private ArrayList<Popup> removal;
	
	public PopupManager() {
		popups = new ArrayList<Popup>();
		removal = new ArrayList<Popup>();
	}
	
	public void addPopup(Popup popup) {
		popups.add(0, popup);
	}
	
	private void removePopup(Popup popup) {
		popup.setWindowManager(null);
		popup.setExternalStyle(null);
		popups.remove(popup);
	}
	
	private void setActive(Popup popup) {
		popups.remove(popup);
		popups.add(0, popup);
	}
	
	public void render() {
		for(int i = popups.size() - 1; i >= 0; i--) {
			popups.get(i).render();
		}
		
		removeMarkedPopups();
	}
	
	public void reset() {
		for(Popup p: popups) {
			p.reset();
		}
	}
	
	private void removeMarkedPopups() {
		for(Popup p: popups) {
			if(p.isMarkForRemoval()) {
				removal.add(p);
			}
		}
		
		for(Popup p: removal) {
			removePopup(p);
		}
		
		removal.clear();
	}
	
	public boolean keyPressed(int key) {
		for(Popup p: popups) {
			if(p.keyPressed(key)) {
				setActive(p);
				return true;
			}
		}
		
		return false;
	}
	
	public boolean keyReleased(int key) {
		for(Popup p: popups) {
			if(p.keyReleased(key)) {
				setActive(p);
				return true;
			}
		}
		return false;
	}
	
	public boolean mousePressed(int x, int y, int button) {
		for(Popup p: popups) {
			if(p.mousePressed(x, y, button)) {
				setActive(p);
				return true;
			}
		}
		return false;
	}
	
	public boolean mouseReleased(int x, int y, int button) {
		for(Popup p: popups) {
			if(p.mouseReleased(x, y, button)) {
				setActive(p);
				return true;
			}
		}
		return false;
	}
	
	public boolean mouseMoved(int x, int y, int button) {
		for(Popup p: popups) {
			if(p.mouseMoved(x, y, button)) {
				return true;
			}
		}
		return false;
	}
	
	public boolean mouseDragged(int x, int y, int button) {
		for(Popup p: popups) {
			if(p.mouseDragged(x, y, button)) {
				return true;
			}
		}
		return false;
	}
	
	public boolean mouseWheelMoved(int movement) {
		for(Popup p: popups) {
			if(p.mouseWheelMoved(movement)) {
				setActive(p);
				return true;
			}
		}
		return false;
	}
}
